<template>
  <div class="set-teacher-wrapper modal" v-loading="pageLoading">
    <div class="set-teacher">
      <header class="header">
        <i></i>
        <span class="modal-title title">
          {{ title }}
        </span>
        <i class="el-icon-close btn" @click="cancel"></i>
      </header>
      <main class="main">
        <p class="desc-text">添加成员</p>
        <el-input
          class="search-input"
          v-model="search"
          prefix-icon="el-icon-search"
          placeholder="请输入成员姓名/手机号码查询"
          @input="inputChange"
          clearable
        ></el-input>
        <div
          class="search-list-wrapper"
          v-loading="loading"
          id="search-user-list"
        >
          <el-checkbox-group
            class="search-list"
            v-model="checkList"
            v-if="searchUserList.length"
          >
            <el-checkbox
              v-for="(user, index) in searchUserList"
              :key="`search-user-${user.UserId}-${index}`"
              :label="user.UserId"
            >
              {{ user.UserName }}({{ user.Phone }})
            </el-checkbox>
          </el-checkbox-group>
          <span class="sarch-tip-text" v-else>暂无查询用户</span>
        </div>

        <!-- <div class="line"></div> -->
        <p class="desc-text">当前成员</p>
        <ul class="curr-list">
          <li
            v-for="{ UserId, UserName, Phone } in localUserList"
            :key="UserId"
          >
            <span class="teacher-name"> {{ UserName }}（{{ Phone }}）</span>
            <span class="remove-btn" @click="toRemove(UserId)">移除</span>
          </li>
        </ul>
      </main>
      <footer class="footer">
        <button class="cancel-btn" @click="cancel">取消</button>
        <button class="confirm-btn" @click="confirm">确定</button>
      </footer>
    </div>
  </div>
</template>
<script>
import { debounce } from '@/utils/utils';
import { mapGetters } from 'vuex';
export default {
  name: '',
  components: {},
  props: {
    currNav: { type: Object, required: true },
    settingInfo: { type: Object, required: true },
    schoolId: { type: Number, required: true },
  },
  data() {
    return {
      search: '',
      searchUserList: [],
      localUserList: [],
      checkList: [],
      loading: false,
      pageLoading: false,
      searchTotal: 0,
      page: 1,
      pageSize: 20,
      debouncedSearch: null, // 添加防抖函数实例
    };
  },
  computed: {
    ...mapGetters('user', ['userId']),
    title() {
      const { grade_name, subject_name, role_name } = this.settingInfo;
      return this.currNav.level === 3
        ? `${grade_name} | ${subject_name}`
        : role_name;
    },
  },
  watch: {},
  mounted() {
    this.localUserList = JSON.parse(
      JSON.stringify(this.settingInfo.user_list || [])
    );
    this.checkList = this.localUserList.map((e) => e.UserId);

    // 初始化防抖函数
    this.debouncedSearch = debounce(() => {
      this.page = 1;
      this.getUserList();
    }, 500);

    this.$watch(
      () => {
        return this.checkList;
      },
      () => {
        this.setlocalUserList();
      }
    );

    const dom = document.querySelector('#search-user-list');
    dom && dom.addEventListener('scroll', this.handleScroll);
  },
  beforeUnmount() {
    const dom = document.querySelector('#search-user-list');
    dom && dom.removeEventListener('scroll', this.handleScroll);
    
    // 清理防抖函数
    if (this.debouncedSearch && this.debouncedSearch.cancel) {
      this.debouncedSearch.cancel();
    }
  },
  methods: {
    handleScroll(e) {
      const scrollTop = e.target.scrollTop;
      const ITEM_HEIGHT = 40;
      const CONTAINER_HEIGHT = 110;
      if (
        scrollTop + CONTAINER_HEIGHT + 10 >=
          this.searchUserList.length * ITEM_HEIGHT &&
        this.searchUserList.length < this.searchTotal
      ) {
        this.loading = true;
        this.page = this.page + 1;
        this.getUserList();
      }
    },

    inputChange() {
      // 使用预定义的防抖函数
      this.debouncedSearch();
    },
    async getUserList() {
      if (this.search === '') {
        this.searchUserList = [];
        this.loading = false;
        return;
      }
      this.loading = true;
      const {
        F_user_list,
        F_page_info: { F_total },
      } = await this.$api.getUsers({
        F_name: this.search,
        F_page: this.page,
        F_limit: this.pageSize,
        F_school_id: this.schoolId,
      });
      this.searchTotal = F_total;
      const list = F_user_list.map(
        ({ F_user_id, F_user_name, F_user_account }) => ({
          UserId: F_user_id,
          UserName: F_user_name,
          Phone: F_user_account,
        })
      );
      this.searchUserList =
        this.page === 1 ? list : this.searchUserList.concat(list);
      this.loading = false;
    },
    setlocalUserList() {
      if (this.localUserList.length === this.checkList.length) return;
      if (this.localUserList.length > this.checkList.length) {
        // 证明是移除一个的操作
        this.localUserList = this.localUserList.filter((e) =>
          this.checkList.includes(e.UserId)
        );
      } else {
        // 证明是新增一个的操作
        const item = this.searchUserList.find(
          (e) => e.UserId === this.checkList[this.checkList.length - 1]
        );
        this.localUserList.push(item);
      }
    },
    toRemove(id) {
      const index = this.localUserList.findIndex((e) => e.UserId === id);
      this.localUserList.splice(index, 1);
      this.checkList = this.localUserList.map((e) => e.UserId);
    },
    cancel() {
      this.$emit('cancel');
    },
    async confirm() {
      const { level } = this.currNav;
      const { grade_id, subject_id, role_id } = this.settingInfo;
      let params =
        level === 3
          ? { F_grade_id: grade_id, F_subject_id: subject_id }
          : { F_role_id: role_id };
      params = {
        ...params,
        F_user_ids: this.checkList.join(','),
        F_school_id: this.schoolId,
        F_creator_id: this.userId,
        F_level_id: level,
      };
      this.pageLoading = true;
      try {
        const { F_responseNo, F_responseMsg } =
          await this.$api.updateRoleUserList(params);
        if (F_responseNo === 10000) {
          this.$toast('设置成功');
          this.$emit('update');
        } else {
          this.$toast(F_responseMsg);
        }
      } catch (e) {
        console.error(e);
      }
      this.pageLoading = false;
    },
  },
};
</script>
<style lang="less" scoped>
.set-teacher {
  box-sizing: border-box;
  width: 480px;
  height: 530px;
  padding: 0 24px;
  background-color: #fff;
  border-radius: 8px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  display: flex;
  flex-direction: column;
  .header {
    height: 51px;
    font-size: 18px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.9);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .main {
    flex: 1;
    overflow-y: auto;
    text-align: left;
    display: flex;
    flex-direction: column;
    .desc-text {
      color: #040b1a;
      line-height: 60px;
    }
    .sarch-tip-text {
      font-size: 15px;
      color: rgba(0, 0, 0, 0.8);
    }
    .search-list-wrapper {
      box-sizing: border-box;
      width: 100%;
      height: 130px;
      padding: 10px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      overflow-y: auto;
    }
    .search-list {
      :deep(.el-checkbox) {
        display: block;
        margin: 0;
        height: 40px;
        display: flex;
        align-items: center;
        .el-checkbox__label {
          font-size: 15px;
        }
      }
      :deep(.el-checkbox__input.is-checked + .el-checkbox__labe) {
        color: #009cff !important;
      }
    }
    .line {
      width: 100%;
      height: 1px;
      background-color: rgba(4, 11, 26, 0.15);
      margin-top: 24px;
    }
    .curr-list {
      flex: 1;
      overflow-y: auto;
      li {
        height: 40px;
        line-height: 40px;
        margin-bottom: 7px;
        display: flex;
        justify-content: space-between;
        color: #009cff;
        background-color: rgba(218, 241, 255, 0.35);
        padding: 0 10px;
        border-radius: 4px;
        .remove-btn {
          cursor: pointer;
        }
      }
    }
  }
  .footer {
    height: 60px;
    line-height: 60px;
    text-align: center;
    button {
      box-sizing: border-box;
      width: 72px;
      height: 36px;
      border-radius: 4px;
      outline: none;
      border: none;
      cursor: pointer;
    }
    .cancel-btn {
      margin-right: 24px;
      color: #606266;
      background-color: #fff;
      border: 1px solid #dcdfe6;
    }
    .confirm-btn {
      color: #fff;
      background-color: #009cff;
    }
  }
}
</style>
